package com.credithc.signature.job.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;

/**
 * 描述：字节工具类<br/>
 * 作者：sunyang
 * 创建：2019/6/5 10:49
 * 版本：v1.0.0<br/>
 */
@Slf4j
public class ByteUtil {

    public static byte[] grow(byte[] src, int size) {
        byte[] tmp = new byte[src.length + size];
        System.arraycopy(src, 0, tmp, 0, src.length);
        return tmp;
    }

    public static byte[] readLoopData(InputStream in) throws IOException {
        byte[] dataTemp = new byte[2048];
        byte[] temp = new byte[1024];
        try {
            int readTotal = 0;
            int readLength;
            while ((readLength = in.read(temp)) != -1){
                if (readLength+readTotal > dataTemp.length) {
                    dataTemp = ByteUtil.grow(dataTemp, 2048);
                }
                System.arraycopy(temp,0,dataTemp,0,readLength);
                readTotal += readLength;
            }
            byte[] data = new byte[readTotal];
            System.arraycopy(dataTemp,0,data,0,readTotal);
            return data;
        } catch (Exception e) {
            log.error("读取数据失败", e);
            throw new RuntimeException(e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // 不做处理
            }
        }
    }
}
